﻿using Rampastring.Tools;
using System.Collections.Generic;
using System.IO;

namespace ClientCore.INIProcessing
{
    /// <summary>
    /// Pre-processes INI files.
    /// Allows sections to inherit other sections.
    /// </summary>
    public class IniPreprocessor
    {
        public void ProcessIni(string sourceIniPath, string destinationIniPath)
        {
            File.Delete(destinationIniPath);

            if (!File.Exists(sourceIniPath))
                return;

            var iniFile = new IniFile(sourceIniPath);
            List<string> sections = iniFile.GetSections();
            sections.ForEach(sectionName => ProcessSection(iniFile, sectionName));
            iniFile.Comment = $"generated by DTA CnCNet client, see /Base/{Path.GetFileName(sourceIniPath)} for the original";

            iniFile.WriteIniFile(destinationIniPath);
        }

        /// <summary>
        /// Processes an INI section and applies its potential base section.
        /// Returns the INI section. Works recursively.
        /// </summary>
        /// <param name="iniFile">The INI file.</param>
        /// <param name="sectionName">The name of the section to process.</param>
        private IniSection ProcessSection(IniFile iniFile, string sectionName)
        {
            IniSection section = iniFile.GetSection(sectionName);
            if (section == null)
                return null;

            string baseSectionName = section.GetStringValue("BaseSection", string.Empty);
            if (string.IsNullOrWhiteSpace(baseSectionName))
                return section;

            IniSection baseSection = ProcessSection(iniFile, baseSectionName);
            if (baseSection == null)
                return section;

            foreach (var kvp in baseSection.Keys)
            {
                if (!section.KeyExists(kvp.Key))
                    section.AddKey(kvp.Key, kvp.Value);
            }

            return section;
        }
    }
}
